package hackbard.piratradar;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import com.google.android.maps.GeoPoint;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;
import android.util.Log;
import android.view.Gravity;
import android.widget.Toast;
import android.location.GpsSatellite;
import android.location.GpsStatus;

/******************************************************
 * AUA, alles grosser Murks bisher, weil:
 * die Reihenfolge requestuopdates, getlastknown, removeupdates
 * nicht funktioniert, weil das GPS nie fertig wird
 * (dauert, bis das ding mit den satelliten zufriden is)
 * als timer _muss_ man also den updateintervall hernehmen und
 * erst im callback wenn stop kommt daten senden.
 *
 * (sonst steht im lastknown immer *irgendwas*)
 *
 * Der service selber hatte auch irgenwelche Macken,
 * deswegen neu......
 * oder wie der niederlaender sagen wuerde 'afgeramt'
 ******************************************************/







public class MonitorService extends Service implements LocationListener, GpsStatus.Listener{
	/**
	 * @see android.app.Service#onBind(Intent)
	 */

	GeoPoint gsm;
	private TelephonyManager tm;
    private GsmCellLocation location;
	private int cid, lac;
	private Timer timer = new Timer();
	private int looping = 0;
	public Handler mHandler;
    private LocationManager lm;
    double  lat = 0, lon = 0;
	long idtime,lastid;
	double cord[];
	GsmLoc loc;
	
	/********** alt ****/
	public static final String PREFS_NAME = "PiratRadar";
	private Integer _UPDATE_ = 8;
	/********* /alt ***********/
	
	
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Put your code here
		return null;
	}

	/**
	 * @see android.app.Service#onCreate()
	 */
	@Override
	public void onCreate() {
		// TODO Put your code here
		
		int delay = 2*60*1000; //zwei minuten (U/S Bahn)

		 SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
		
		   if ((settings.getLong("gpsupdate", 0) <= 5) && settings.getInt("update", 1) < _UPDATE_){
               SharedPreferences.Editor editor = settings.edit();
               editor.putInt("update", _UPDATE_);
               editor.putLong("gpsupdate", 5);
               Toast.makeText(getBaseContext(),
                               "PiratenRadar einstellungen aktualisiert!",
                               Toast.LENGTH_SHORT).show();
               delay = (int)settings.getLong("gpsupdate",0);
		   }
		
		
		
		
	   	Toast t = Toast.makeText(getBaseContext(), "Started",
     		      Toast.LENGTH_LONG);
      	t.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
      	t.show();
        
      	
      	if (settings.getBoolean("gpsautoupdater", true)) 
      		{
      		
      		Log.w("Radar", "time set to " + delay);
      		lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
      		lm.addGpsStatusListener(this);
      		lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, (delay * 60 * 1000), 0,this);
      		if(lm.isProviderEnabled(LocationManager.GPS_PROVIDER) == false)
      			{
            
      			loc = new GsmLoc();
      		    		
      			timer.scheduleAtFixedRate( new TimerTask() {
    			
	            
      				public void run() {
      					Log.w("Radar", "Pirate Radar starting refresh");
      					cord = loc.getgsm(getBaseContext());
      					Map<String, String> kvPairs = new HashMap<String, String>();
      					kvPairs.put("lon", String.valueOf(cord[1]));
      					kvPairs.put("lat", String.valueOf(cord[0]));
      					SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
      					kvPairs.put("nick", settings.getString("nick", "anonymus"));
      					/*
      					 * TODO: DELETE test url2 ;;; ja, aber spaeter :-)
      					 */
      					String url2 =  "http://spitzner.org/pos.php";
      					String url = "http://piratenradar.de/output.php";
      					
      					try {
      						HTTPPoster.doPost(url, kvPairs);
      						/*
      						 * TODO: DELETE test url2 psot
      						 */
      						} 
      					catch (IOException e) 
    	            		{
    	                    Log.w("Radar", "1: " + e.getMessage());
    	            		}
      					try {
      						HTTPPoster.doPost(url2, kvPairs);
      						} 
      					catch (IOException e2) 
      						{
      						Log.w("Radar", "2: " + e2.getMessage());
    	                }
    	                Log.w("Radar", "Pirate Radar Ending refresh");

      				}
      			}, 0, delay * 60 * 1000);
      		
      			}
      		}
      	
      	
	}
	
	@Override
	public void onDestroy() {
    	timer.cancel();
    	lm.removeGpsStatusListener(this);
    	lm.removeUpdates(this);
    	Log.i("Radar","onDestroy complete");
	
	}

	
	
	private void send_data(String what,GeoPoint p)
	{
		String urlString = "http://gate.spitzner.org/Radar.php?";
		urlString += what + "&lat=" + p.getLatitudeE6() + "&lon=" + p.getLongitudeE6();		
		try 
			{
			URL url = new URL(urlString); 
			URLConnection conn = url.openConnection();
			conn.connect();
			conn.getContent();
		}
		catch(IOException e)
			{
	    	String strResult = "Error!\n" + e.getMessage();
			Toast t = Toast.makeText(getBaseContext(), strResult,
	     		      Toast.LENGTH_LONG);
	     	t.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
	     	t.show();
	     	Log.i("Radar","aua senddata " + e.getMessage());
	
			}
		Log.i("Radar","Data sent !");
	}
	
	

	

	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub
		lat = location.getLatitude();
		lon = location.getLongitude();
		Log.i("Radar","change:" + location.getAccuracy() + " " + lat + " " + lon);
	}

	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
		Log.i("Radar","Provider dis");
	}

	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
		Log.i("Radar","Provider ena");
	}

	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
		Log.i("Radar","statuschanged");
	}

	public void onGpsStatusChanged(int event) {
		// TODO Auto-generated method stub
		switch (event) {
		case GpsStatus.GPS_EVENT_FIRST_FIX:
			String strResult = "Got Fix";
			Toast t = Toast.makeText(getBaseContext(), strResult,
	     		      Toast.LENGTH_LONG);
	     	t.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
	     	t.show();
	     	Log.i("Radar","Got Fix");
			/*if(lat != 0)
				{
				GeoPoint p = new GeoPoint(
				      (int) (lat * 1E6), 
		              (int) (lon * 1E6));

				send_data("type=gps&id="+idtime,p);
				Log.i("Radar", "gps sent");
				}*/
	     	break;

		case GpsStatus.GPS_EVENT_SATELLITE_STATUS:

			GpsStatus status = lm.getGpsStatus(null);

			Iterator<GpsSatellite> it = status.getSatellites().iterator();
			int count = 0;
			while (it.hasNext()) {
				count++;
				GpsSatellite oSat = (GpsSatellite) it.next();
				//Log.i("Radar","onGpsStatusChange: Satellites:"
				//				+ oSat.getSnr());
			}
			Log.i("Radar","# of sats: " + count);

			//SetSatelliteInfo(count);
			break;

		case GpsStatus.GPS_EVENT_STARTED:
			//SetStatus("GPS Started, waiting for fix");
			Log.i("Radar","Wait for Fix (event start)");
			break;

		case GpsStatus.GPS_EVENT_STOPPED:
	//		SetStatus("GPS Stopped");
			
			Log.i("Radar","GPS stop");
			Location lo = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
			Log.i("Radar","acc:" + (int)lo.getAccuracy());
			strResult = "GPS akkurat auf " + (int)lo.getAccuracy() + "m";
			t = Toast.makeText(getBaseContext(), strResult,
	     		      Toast.LENGTH_LONG);
	     	t.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
	     	t.show();
            Log.w("Radar","sending data");
            String url = "http://piratenradar.de/output.php";
            Map<String, String> kvPairs = new HashMap<String, String>();
            kvPairs.put("lon", String.valueOf(lo.getLongitude()));
            kvPairs.put("lat", String.valueOf(lo.getLatitude()));
            SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
            kvPairs.put("nick", settings.getString("nick", "anonymus"));
            /*
             * TODO: DELETE test url2 ;;; ja, aber spaeter :-)
             */
            String url2 =  "http://spitzner.org/pos.php";
            try {
                    HTTPPoster.doPost(url, kvPairs);
            /*
             * TODO: DELETE test url2 psot
             */
            	} 
            catch (IOException e) 
            		{
                    Log.w("Radar", "1: " + e.getMessage());
            		}
            try {
                 HTTPPoster.doPost(url2, kvPairs);
                } 
            catch (IOException e2) 
            	{
                Log.w("Radar", "2: " + e2.getMessage());
                }
                Log.w("Radar", "Pirate Radar Ending refresh");

			break;
		}

	}
	

	
	
}

	

	

	
	
	
	

	
	


